package com.xianshijian.oauth.resource.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xianshijian.oauth.common.entity.OAuth;
import com.xianshijian.oauth.common.entity.OAuthResult;
import com.xianshijian.oauth.resource.service.ResourceService;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

/**
 * 资源服务接口.
 * 
 * @author lzj
 *
 */
@Controller
public class ResourceController {

    @Autowired
    private ResourceService resourceService;
    
    private static final Logger LOG = LoggerFactory.getLogger(ResourceController.class);

    @RequestMapping(value = "/users/{accessToken}", method = RequestMethod.GET)
    public @ResponseBody Object userInfo(HttpServletRequest request, @PathVariable String accessToken) {
        try {

            //验证access_token
            if (StringUtils.isBlank(accessToken) || !resourceService.checkAccessToken(accessToken)) {
            	return OAuthResult.build(OAuth.StatusCode.ACCESS_TOKEN_ERROR, "客户端验证失败，失败原因：错误的AccessToken或者AccessToken过期了");
            }         
            
            //返回用户信息
            return resourceService.findUserByAccessToken(accessToken);
        } catch (Exception e) {
        	//打印错误日志
        	String msg = "调用userInfo出错 : {" + e.getMessage() + "}";
			String errMsg = new StringBuilder(msg).append(", 请求参数为:[{}]").toString();
			LOG.error(errMsg, Arrays.asList(new Object[] { request }));
			LOG.error("错误信息:", e);
			throw new RuntimeException(msg, e);
        }
    }
}
